# https://zhuanlan.zhihu.com/p/68197380?utm_id=0
import sys
from zipfile import ZipFile

from bs4 import BeautifulSoup
from qgis.PyQt.QtCore import (pyqtSignal, Qt)
from qgis.PyQt.QtWidgets import *
from qgis.core import QgsRectangle, QgsVectorLayer, QgsFeature, QgsWkbTypes, QgsPointXY
from qgis.gui import QgsRubberBand, QgsMapTool

# https://www.cnblogs.com/zhiyiYo/p/15676079.html

if __name__ != '__main__':
    from .photoviewer import *
    from .photowidget import Photowidget






class PhotomapTool(QgsMapTool):
    afterLeftClick = pyqtSignal()
    afterRightClick = pyqtSignal()
    afterDoubleClick = pyqtSignal()
    feature_selected = pyqtSignal(QgsFeature)

    def __init__(self, map_canvas):
        QgsMapTool.__init__(self, map_canvas)
        self.map_canvas = map_canvas

        # self.drawSelf = drawSelf
        # self.drawSelf.rb = None
        self.is_pressed = False
        self.current_file = None
        self.photosDLG = None
        self.setCursor(Qt.PointingHandCursor)
        self.feature_selected.connect(self.showphoto)

    def set_current_file(self, current_file):
        self.current_file = current_file
        # print(f'currentlayer:{self.currentLayer()}')
        try:
            self.zip_file = ZipFile(self.current_file, 'r')
            self.file_list = self.zip_file.namelist()
        except Exception as e:
            print(f'zipfile error:{e}')
        # self.zip_file.close()

    def showphoto(self, feature):
        """当用户选择要素后被调用"""
        print("You clicked on feature {}".format(feature['Name']))
        try:
            soup = BeautifulSoup(feature['description'], 'html.parser')
            img_paths = []
            for img_path in soup.find_all('img'):
                img_paths.append(img_path['src'])
            imgs = []
            for img_path in img_paths[0:20]:
                data = self.zip_file.open(img_path).read()
                img = QImage.fromData(data)
                imgs.append(img)
            self.photosDLG = Photowidget(imgs)
            self.photosDLG.setWindowTitle(feature['Name'])
            self.photosDLG.show()
        except Exception as e:
            print(f'no description:{e}')

    def canvasPressEvent(self, event):
        if event.button() == 1:
            # sigeal : keep photo viewer on top of other windows
            self.is_pressed = True

    def canvasReleaseEvent(self, event):
        if self.is_pressed:
            layers = self.map_canvas.layers()
            p = self.toMapCoordinates(event.pos())
            w = self.map_canvas.mapUnitsPerPixel() * 10
            try:
                rect = QgsRectangle(p.x() - w, p.y() - w, p.x() + w, p.y() + w)
            except:
                return
            layers_selected = []
            for layer in layers:
                if type(layer) == QgsVectorLayer:
                    if layer.storageType() == 'LIBKML':
                        self.set_current_file(layer.source().split('|')[0])
                        select_rect = self.map_canvas.mapSettings().mapToLayerCoordinates(layer, rect)
                        layer.selectByRect(select_rect)
                        selected_features = layer.selectedFeatures()
                        if selected_features:
                            layers_selected.append(layer)
                            feature = selected_features[0]
                            self.feature_selected.emit(feature)
                            return
            else:
                pass

    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('PhotoWindow', message)

    def showrubber(self, rect):
        if self.rubberBand:
            self.rubberBand.reset()
        self.rubberBand = QgsRubberBand(self.map_canvas, QgsWkbTypes.PolygonGeometry)
        self.rubberBand.setColor(Qt.red)
        self.rubberBand.setWidth(1)
        self.rubberBand.reset(QgsWkbTypes.PolygonGeometry)
        # rubberBand.addGeometry(rect)
        self.rubberBand.addPoint(QgsPointXY(rect.xMinimum(), rect.yMinimum()), False)
        self.rubberBand.addPoint(QgsPointXY(rect.xMaximum(), rect.yMinimum()), False)
        self.rubberBand.addPoint(QgsPointXY(rect.xMaximum(), rect.yMaximum()), False)
        self.rubberBand.addPoint(QgsPointXY(rect.xMinimum(), rect.yMaximum()), True)
        self.rubberBand.show()

        # rubberBand.reset()


if __name__ == '__main__':
    from photoviewer import *
    import zipfile

    zip_file = zipfile.ZipFile("U:\桑植县2023年控违治违工作项目\工作数据\测量数据\高家坪\高家坪.kmz", 'r')
    file_list = zip_file.namelist()
    print(file_list)
    img_paths = file_list[5:6]
    print(img_paths)
    imgs = []
    for img_path in img_paths:
        data = zip_file.open(img_path).read()
        img = QImage.fromData(data)
        imgs.append(img)
    zip_file.close()
    app = QApplication(sys.argv)
    photosDLG = Photowidget(imgs)
    photosDLG.show()
    app.exec_()
    # app.exitQgis()
